package view;

import constant.ConstRole;
import constant.ConstWebPage;
import io.netty.util.CharsetUtil;
import pond.web.Render;
import service.DataBaseService;
import service.WebPageService;
import pond.common.STREAM;
import pond.common.STRING;
import pond.common.f.Function;
import pond.db.DB;
import pond.db.connpool.ConnectionPool;
import pond.web.CtxHandler;
import pond.web.HttpCtx;
import pond.web.restful.API;
import pond.web.restful.ParamDef;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static pond.common.f.Tuple.pair;
import static pond.web.restful.ParamDef.*;
import static pond.web.restful.ResultDef.*;
/**
 * Created by sky_wang on 2017/4/11.
 */
public class ReportView {

    private Function.F0<List<ConstRole>> getRoleList = null;
    private DataBaseService dataBaseService = null;
    private String path = "";

    public ReportView(DB db, Function.F0<List<ConstRole>> f, File reportDataDir, String urlPath)
    {
        this.getRoleList = f;
        this.dataBaseService = new DataBaseService(db, reportDataDir, getTableMap());
        if (STRING.notBlank(urlPath))
        {
            path = urlPath;
        }
    }

    public CtxHandler server() {
        return new API() {
            final Class reportViewClass = ReportView.class;
            final String reportViewPrefix = "web/";
            {
                get("/data/base", (req, resp) -> {
                    if (getRoleList !=null)
                    {
                        Map<String,Object>   dataMap = new HashMap<>();
                        List<String>    moduleList = new ArrayList<>();
                        List<ConstRole> list       = getRoleList.apply();
                        for (ConstRole constRole :list)
                        {
                            moduleList.add(constRole.getName());
                        }
                        dataMap.put("module",moduleList);

                        resp.render(Render.json(dataMap));
                    }
                    else
                    {
                        resp.send(403, "no login");
                    }


                });
                use("/table/*",    new Table(dataBaseService));
                use("/express/*",  new Express(dataBaseService));
                use("/report/*",   new Report(dataBaseService));
                use("/view/*",     new View(dataBaseService));
                use("/relation/*", new Relation(dataBaseService));

                get("/", API.def(
                        resourceAsFile("index.html"),
                        (ctx, render) ->
                                ctx.result(render, pair(reportViewClass, reportViewPrefix + "index.html"))
                ));

                get("/:file", API.def(
                        path("file"),
                        error(403, "403"),
                        resourceAsFile("file"),
                        (ctx, file, e403, render) -> ctx.result(render, pair(reportViewClass, reportViewPrefix + file))
                ));
                get("/css/images/:file",
                        API.def(
                                path("file"),
                                resourceAsFile("css image files"),
                                (ctx, file, render) ->
                                        ctx.result(render, pair(reportViewClass, reportViewPrefix + "css/images/" + file))
                        ));
                get("/css/:file",

                        API.def(
                                path("file"),
                                resourceAsFile("css files"),
                                (ctx, file, render) ->
                                        ctx.result(render, pair(reportViewClass, reportViewPrefix + "css/" + file))
                        ));

                get("/fonts/:file", API.def(
                        path("file"),
                        resourceAsFile("fonts"),
                        (ctx, file, render) ->
                                ctx.result(render, pair(reportViewClass, reportViewPrefix + "fonts/" + file))
                ));
                get("/images/:file", API.def(
                        path("file"),
                        resourceAsFile("images"),
                        (ctx, file, render) ->
                                ctx.result(render, pair(reportViewClass, reportViewPrefix + "images/" + file))
                ));
                get("/lang/:file", API.def(
                        path("file"),
                        resourceAsFile("lang"),
                        (ctx, file, render) ->
                                ctx.result(render, pair(reportViewClass, reportViewPrefix + "lang/" + file))
                ));
                get("/js/:file", API.def(
                        path("file"),
                        resourceAsFile("js"),
                        (ctx, file, render) ->
                        {
                            if ("main.js".equals(file)) {
                                InputStream in = reportViewClass.getClassLoader().getResourceAsStream( reportViewPrefix + "js/" + "main.js");
                                String tmpl = null;
                                try {
                                    tmpl = STREAM.readFully(in, CharsetUtil.UTF_8);
                                    if (STRING.notBlank(path)) {
                                        tmpl = tmpl.replace("rp_base_url_value", path);
                                    }
                                    HttpCtx httpCtx = ((HttpCtx) ctx);
                                    httpCtx.resp.header("Content-Type", "text/javascript");
                                    httpCtx.resp.send(200, tmpl);
                                    ctx.setHandled();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            else
                            {
                                ctx.result(render, pair(reportViewClass, reportViewPrefix + "js/" + file));
                            }

                        }

                ));
                otherwise(API.def(
                        error(404, "404"),
                        (ctx, e404) -> ctx.result(e404, "not found")
                ));

            }
        };
    }

    public Map<String,String> getTableMap(){
        return new HashMap<String,String>(){
            {
                put("view_for_express",
                        "CREATE TABLE `view_for_express` (" +
                                "  `vid` varchar(256) DEFAULT NULL," +
                                "  `expressions` text," +
                                "  `members` text," +
                                "  `group_name` varchar(256) DEFAULT NULL," +
                                "  `is_has_exp_group` varchar(8) DEFAULT NULL," +
                                "  `header_name` varchar(256) DEFAULT NULL" +
                                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");

                put("view_for_report",
                        "CREATE TABLE `view_for_report` (" +
                                "  `vid` varchar(256) DEFAULT NULL," +
                                "  `view_for_grid_id` varchar(256) DEFAULT NULL," +
                                "  `report_name` varchar(256) DEFAULT NULL," +
                                "  `report_data` varchar(1024) DEFAULT NULL" +
                                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");

                put("view_for_grid",
                        "CREATE TABLE `view_for_grid` (" +
                                "  `view_name` varchar(64) DEFAULT NULL," +
                                "  `view_sql` text," +
                                "  `grid_options` text," +
                                "  `vid` varchar(64) DEFAULT NULL," +
                                "  `main_table` varchar(64) DEFAULT NULL," +
                                "  `query_html` text," +
                                "  `query_ids` text," +
                                "  `show_tables` text," +
                                "  `show_columns` text," +
                                "  `relational_data_tables` text," +
                                "  `template_name` varchar(64) DEFAULT NULL," +
                                "  `select_columns` text," +
                                "  `cols_of_sub_groups` text," +
                                "  `is_single_group` varchar(8) DEFAULT NULL," +
                                "  `template_columns` text," +
                                "  `auto_id` int(11) DEFAULT NULL" +
                                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");

                put("view_for_relation",
                        "CREATE TABLE `view_for_relation` (" +
                                "  `vid` varchar(256) DEFAULT NULL," +
                                "  `relation_data_default` text," +
                                "  `relation_data_config` text" +
                                ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
            }
        };
    }

}
